package DCSource;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class Statereader {
	private int by=0;
	private int maxSize=0;
	private boolean useable=false;
	private BufferedInputStream reader;
	private int speed = 20480;
	public Statereader(String file){
		File t = new File(file);
		if (t.exists()){
			try {
				FileInputStream zw = new FileInputStream(t);
				reader = new BufferedInputStream(zw);
				zw.close();
				try {
					maxSize=reader.available();
				} catch (IOException e) {
					maxSize=-1;
				}
				useable = true;
			} catch (Exception e) {
				
			}
		}
	}
	public boolean isUseable(){
		return useable;
	}
	public void setSpeed(int NeedSpeed){
		if (useable){
			if (20480>NeedSpeed){
				if (NeedSpeed>0){
					speed = NeedSpeed;
				}
			}
		}
	}
	public int getCount(){
		if (useable){
			return by;
		}else{
			return -1;
		}
	}
	public int getSize(){
		if (useable){
			return maxSize;
		}else{
			return -1;
		}
	}
	public int getToGetSize(){
		if (useable){
			try {
				return reader.available();
			} catch (IOException e) {
				return -1;
			}
		}else{
			return -1;
		}
	}
	public boolean hasnext(){
		if (useable){
			if (by<maxSize){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	public int getNext(byte[] b){
		if (useable){
			int readed = 0;
			int went = speed;
			try {
				if (by+went>reader.available()){
					went = reader.available();
				}
				if (went>b.length){
					went = b.length;
				}
			} catch (IOException e) {
				went = -1;
			}
			if (went>0){
				try {
					readed = reader.read(b, 0, went);
					by+=went;
				} catch (IOException e) {
				}
				return readed;
			}else{
				return -1;
			}
		}else{
			return -1;
		}
	}
	public boolean reset(){
		if (useable){
			try {
				reader.reset();
				by = 0;
				return true;
			} catch (IOException e) {
				return false;
			}
		}else{
			return false;
		}
	}
	public boolean reInit(String file){
		File t = new File(file);
		if (t.exists()){
			try {
				FileInputStream zw = new FileInputStream(t);
				reader = new BufferedInputStream(zw);
				useable = true;
				by = 0;
				return true;
			} catch (FileNotFoundException e) {
				return false;
			}
		}else{
			return false;
		}
	}
	public boolean close(){
		try {
			reader.close();
			return true;
		} catch (IOException e) {
			return false;
		}
	}
}
